// pages/live/live.js
import Wx from "../../common-wx/wx"
import ECache from "../../utils/cache";
import {Api} from "../../network/api";
import Router from "../../utils/router";
const fetch = require('../../utils/fetch');
const uploadFile = require('../../utils/uploadFile');
const TIM = require('../../utils/tim-wx');
let tim;
let timer1;
let timer2;
Page({
    /**
     * 页面的初始数据
     */
    data: {
        isSend: false,              // 防止重复发送请求
        addInfo: {
            live_image: '',         // 直播间封面
            anchor_desc: '',        // 主播描述
            video_desc: '',         // 直播间描述
            shop_id: '',            // 店铺id
            shop_image: '',         // 店铺图片
            shop_name: '',          // 店铺名字
            shop_address: '',       // 店铺地址
            goods_list: [],         // 直播商品信息
            key: '',                // 登录key
            video_classified: '',   // 直播间分类id
        },
        addSellList: [],            // 添加商品列表
        beautyInfo: {
            beauty: 5,              // 美颜
            whiteness: 5,           // 美白
        },
        showBeauty: false,          // 显示美颜弹窗
        showFactory: false,         // 显示工厂列表弹窗
        showTags: false,            // 显示分类标签
        selectFactory: false,       // 选择工厂
        factoryList: [],            // 工厂列表
        factoryKeywords: '',        // 工厂关键字
        factoryPage: '0',           // 工厂列表分页
        factoryPageTotal: '',       // 工厂列表总页数
        showGoods: false,           // 显示商品列表
        oldAddShopId: '',           // 先前选择店铺id
        tagsList: '',               // 分类标签列表
        goodsOption: {
            storeId: -1,
            cateId: -1,
            storeCateId: -1,
            queryString: '',
            sortItems: [],
            attributes: [],
            brandNames: [],
            stockFilter: -1,
            pageNum: 0,
            pageSize: 10
        },                          // 商品分页
        goodsPageTotal: 1,          // 商品总页数
        goodsList: [],              // 商品列表
        tabCur: 0,                  // 商品列表切换
        room_id: '',                // 房间号
        infoData: {},               // 主体信息
        device: 'front',            // 摄像头方向第一次设置有效
        showConfirmBar: false,      // 输入框显示完成
        showUserGoods: false,       // 用户端显示商品
        moveLeft: 0,                // 左滑距离
        moveTop: 0,                 // 上滑距离
        showAnchorGoods: false,     // 主播端显示商品
        anchorGoodsIndex: 1,        // 商品选中Index默认已开售
        liveStop: false,            // 直播结束
        liveMonitorTimer: '',       // 监听定时器
        navigate: false,            // 跳出保留直播
        liveGoods: [],              // 直播中商品
        group_id: '',               // im群组
        account_id: '',             // im设置
        usersig: '',                // im设置
        content: '',                // 内容
        hasRoom: false,             // load获取数据，show则不获取
        msgList: [],                // 消息列表
        scrollTo: '',               // 消息滚动到view
        showAnchorInput: false,     // 主播评论框
        cutomerId: '',              // 商品端用户id
        nickName: '',               // 商品端nickName
        joinList:[],                // 进入消息
        joinAnim: false,            // 加入动画
        orderList:[],               // 订单消息
        orderAnim: false,           // 订单动画
        sellGoodsList: [],          // 开售列表
        sellPage: 0,                // 开售商品页码
        sellPageTotal: 1,           // 开售商品总页数
        follow: false,              // 是否关注工厂
        followCount: 0,             // 关注工厂数
        isJoinGroup: false,         // 判断是否加入群组
        greatCount: 0,              // 点赞数
        like_type: 0,               // 点赞状态
        clickPraise: [],            // 点击点赞数组
        infoCont: {},               // 工厂信息
        shareCount: 0,              // 分享数
        soInputVal: '',             // 主播搜索商品
        liveTimes: '00:00:00',      // 直播时长
        watchNumber:0,              // 观看人数
        dealOrderList: [],          // 成交订单
        dealOrderPage: 0,           // 成交订单页码
        orderStatus: {'1': '待付款', '2': '待发货', '3': '待收货', '4': '已完成', '5': '交易关闭', '6': '交易关闭', '7': '交易关闭'},                           // 订单状态
        orderCount: 0,              // 订单数
        orderAmount: 0,             // 成交额
        noData: false,              // 成交订单翻页
        liveHistory: false,         // 直播回放
        video_url: '',              // 回放视频地址
        anchorid: '',               // 主播id
        isAdd: true,                // 发送给商品后台
        next_room_id: '',           // 下一直播间id
        next_live_image: '/img/live/live_image.png', // 下一直播间封面
        no_next: true,             // 是否有下个直播
        next_swiper: 0,             // 下滑切换后恢复
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let _this = this;
        if (options.room_id && options.room_id != 'undefined') {
            _this.setData({
                room_id: options.room_id
            });
        };
        if (options.video_url && options.video_url != 'undefined') {
            _this.setData({
                video_url: options.video_url
            });
        };
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.setData({
            livePusher: wx.createLivePusherContext('livePusher'),
            livePlayer: wx.createLivePusherContext('livePlayer'),
        });
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        let _this = this;
        // 保持屏幕常亮
        wx.setKeepScreenOn({
            keepScreenOn: true
        });
        if(Wx.getStorage(ECache.LIVE_KEY)) {
            _this.setData({
                isSend: false,
                'addInfo.key': Wx.getStorage(ECache.LIVE_KEY),
                anchorid: Wx.getStorage(ECache.ANCHOR_ID),
                nickName: Wx.getStorage(ECache.NICK_NAME),
                cutomerId: Wx.getStorage(ECache.CUSTOMER_ID)
            });
        }
        else {
            Router.navTo('Login')
        }

        if (_this.data.room_id) {
            _this.LiveInfo();
        }
    },
    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {
        let _this = this;

        wx.setKeepScreenOn({
            keepScreenOn: false,
        });
		

        if(_this.data.isJoinGroup) {
            var message = _this.createText(_this.data.group_id, '退出发送消息成功', 6);
            let promiseTips = tim.sendMessage(message);
            promiseTips.then(function (imResponse) {
                console.log('退出发送消息成功');
				_this.stopTim();
            });
        }
    },
    /**
     * 用户点击分享
     */
    onShareAppMessage: function () {
        this.share();
        return {
            imageUrl: this.data.addInfo.live_image,
            path: '/pages/live/live?room_id=' + this.data.room_id
        }
    },
    // 修改封面
    changeCover() {
        var _this = this;
        wx.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: ['album'],
            success: async function (res) {
                var tempFilePaths = res.tempFilePaths;
                if(_this.data.isSend) {
                    return false;
                }
                _this.setData({
                    isSend: true
                });
                wx.showLoading({
                    title: '上传中'
                });
				
				// 验证
				const {errcode,errmsg} = await uploadFile(res.tempFilePaths[0],Api.ImgCheck)
				
				if(errcode!=0){
					try{wx.hideLoading()}catch(err){};
					Wx.showToastError('封面图片违规:'+errmsg);
					return
				}
				
                uploadFile(res.tempFilePaths[0]).then(res2 => {
                    _this.setData({
                        'addInfo.live_image': res2,
                        isSend: false
                    });
                    try{wx.hideLoading()}catch(err){};
                }).catch(ex => {
                    _this.setData({
                        isSend: false
                    });
                    try{wx.hideLoading()}catch(err){};
                })
            }
        });
    },
    // 是否显示美颜
    changeBeauty() {
        this.setData({
            showBeauty: !this.data.showBeauty
        });
    },
    // 添加搜索商品
    searchGoods(e) {
        let _this = this;
        _this.setData({
            'goodsOption.queryString': e.detail.value,
            'goodsOption.pageNum': 0,
        });
        _this.getGoods();
    },
    // 添加搜索工厂
    searchFactory(e) {
        let _this = this;
        _this.setData({
            'factoryKeywords': e.detail.value,
            'factoryPage': 0,
        });
        _this.getFactory();
    },
    // 是否显示工厂列表
    changeFactory() {
        let _this = this;
        _this.setData({
            showFactory: !_this.data.showFactory,
            factoryKeywords: ''
        });
        if(!_this.data.factoryList.length) {
            _this.getFactory();
        }
    },
    // 加载工厂列表数据
    getFactory() {
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        wx.showLoading({
            title: '加载中'
        });
        fetch(Api.StoreList, {
            method: 'POST',
            data: {
                orderBy: 0,
                keyword: _this.data.factoryKeywords,
                pageNum: _this.data.factoryPage
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            try{wx.hideLoading()}catch(err){};
            _this.setData({
                isSend: false
            });
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            let arr = _this.data.factoryList;
            if(_this.data.factoryPage == '0') {
                arr = [];
                _this.setData({
                    factoryPageTotal: res.totalPage
                });
            };
            arr = arr.concat(res.data);
            _this.setData({
                factoryList: arr,
                factoryPage: +_this.data.factoryPage+ 1
            });
        });
    },
    // 工厂滚动到底部
    scrollFactory() {
        if(this.data.factoryPage > this.data.factoryPageTotal) {
            return false;
        }
        this.getFactory();
    },
    // 选择工厂
    selectFactory(e) {
        let _this = this;
        _this.setData({
            oldAddShopId: _this.data.addInfo.shop_id,
            selectFactory: true,
            showFactory: false,
            'addInfo.shop_id': e.currentTarget.dataset.id,
            'addInfo.shop_name': e.currentTarget.dataset.name,
            'addInfo.shop_image': e.currentTarget.dataset.image,
            'addInfo.shop_address': e.currentTarget.dataset.address,
        });
        if(_this.data.oldAddShopId != _this.data.addInfo.shop_id) {
            // 选择新工厂商品重置
            _this.setData({
                tabCur: 0,
                'goodsOption.sortItems': [],
                'goodsOption.queryString': '',
                'goodsOption.pageNum': 0,
                'goodsOption.storeId': _this.data.addInfo.shop_id,
                addSellList: [],
                'addInfo.goods_list': [],
            })
        };
    },
    // 取消
    cancel() {
        this.setData({
            showFactory: false,
            showGoods: false,
            showTags: false,
        });
    },
    // 显示商品列表
    changeGoods() {
        let _this = this;
        _this.setData({
            showGoods: !_this.data.showGoods
        });
        if(_this.data.goodsOption.pageNum > _this.data.goodsPageTotal) {
            return false;
        }
        _this.getGoods();
    },
    // 根据工厂获取商品列表
    getGoods() {
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        wx.showLoading({
            title: '加载中'
        });
        fetch(Api.SearchSpu, {
            method: 'POST',
            data: _this.data.goodsOption
        }).then(res => {
            try{wx.hideLoading()}catch(err){};
            _this.setData({
                isSend: false
            });
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            let arr = _this.data.goodsList;
            if(_this.data.goodsOption.pageNum == '0') {
                arr = [];
                _this.setData({
                    goodsPageTotal: res.totalPages
                });
            };
            arr = arr.concat(res.datas);
            _this.setData({
                goodsList: arr,
                'goodsOption.pageNum': +_this.data.goodsOption.pageNum + 1
            });
        })
    },
    // 商品滚动到底部
    scrollGoods() {
        if(this.data.goodsOption.pageNum > this.data.goodsPageTotal) {
            return false;
        }
        this.getGoods();
    },
    // 跳转商品详情
    toSkuDetail: function (e) {
        let _this = this;
        let param = e.currentTarget.dataset.param;
        let room_id = _this.data.room_id;
        let anchorId = _this.data.anchorid;
        if (param !== 0 && !param) {
            Wx.showToastError('缺少参数')
        }
        Router.navTo('SkuDetail', '?skuId=' + param + '&roomId=' + room_id + '&anchorId=' + anchorId)
    },
    // 跳转商品详情
    rdtoSkuDetail: function (e) {
        let _this = this;
        let param = e.currentTarget.dataset.param;
        let room_id = _this.data.room_id;
        let anchorId = _this.data.anchorid;
        if (param !== 0 && !param) {
            Wx.showToastError('缺少参数')
        }
        wx.redirectTo({
            url: '/pages/skudetail/skuDetail?skuId=' + param + '&roomId=' + room_id + '&anchorId=' + anchorId
        })
    },
    // 进店选商品
    toStoreIndex: function (e) {
        let _this = this;
        _this.setData({
            oldAddShopId: _this.data.addInfo.shop_id,
            selectFactory: true,
            showFactory: false,
            'addInfo.shop_id': e.currentTarget.dataset.id,
            'addInfo.shop_name': e.currentTarget.dataset.name,
            'addInfo.shop_image': e.currentTarget.dataset.image,
            'addInfo.shop_address': e.currentTarget.dataset.address,
        });
        if(_this.data.oldAddShopId != _this.data.addInfo.shop_id) {
            // 选择新工厂商品重置
            _this.setData({
                tabCur: 0,
                'goodsOption.sortItems': [],
                'goodsOption.queryString': '',
                'goodsOption.pageNum': 0,
                'goodsOption.storeId': _this.data.addInfo.shop_id,
                addSellList: [],
                'addInfo.goods_list': [],
            })
        };
        this.changeGoods();
    },
    // 选择商品
    selectGoods(e) {
        let _this = this;
        let index = e.currentTarget.dataset.index;
        let newArr = _this.data.addInfo.goods_list;
        let newList = _this.data.goodsList;
        let newArr2 = _this.data.addSellList;
        let obj = {
            goods_id: e.currentTarget.dataset.id,
            goods_name: e.currentTarget.dataset.name,
            goods_price: e.currentTarget.dataset.price,
            image_url: e.currentTarget.dataset.url,
            goods_stock: e.currentTarget.dataset.stock,
            goods_code:  e.currentTarget.dataset.code
        }
        let obj2 = {
            spuId: e.currentTarget.dataset.spuid,
            storeId: e.currentTarget.dataset.storeid,
            customerId: _this.data.anchorid,
            spuName: e.currentTarget.dataset.name,
            imageUrl: e.currentTarget.dataset.url,
            price: e.currentTarget.dataset.price,
            sellType: 0,
            skuId:  e.currentTarget.dataset.id
        }
        let repeat = false;
        newList[index].checked = true;
        for (var i = 0; i < newArr.length; i++) {
            if (obj.goods_id == newArr[i].goods_id) {
                newArr.splice(i, 1);
                newArr2.splice(i, 1);
                newList[index].checked = false;
                repeat = true;
                break;
            }
        }
        if(!repeat) {
            newArr.push(obj);
            newArr2.push(obj2);
        }

        _this.setData({
            goodsList: newList,
            'addInfo.goods_list': newArr,
            addSellList: newArr2
        });
    },
    // tab切换
    changeTab(e) {
        let _this = this;
        let sortItems = _this.data.goodsOption.sortItems;
        if(e.currentTarget.dataset.index == '0') {
            // 综合
            sortItems = []
        }
        else if(e.currentTarget.dataset.index == '1') {
            // 销量
            sortItems = [{field: "saleNum", order: 1}]
        }
        else if(e.currentTarget.dataset.index == '2') {
            // 新品
            sortItems = [{field: "skuUpTime", order: 1}]
        }
        else if(e.currentTarget.dataset.index == '3') {
            if(sortItems[0].field == 'price' && sortItems[0].order == '0') {
                // 价格降序
                sortItems = [{field: "price", order: 1}]
            }
            else {
                // 价格升序
                sortItems = [{field: "price", order: 0}]
            }
        }
        console.log(sortItems, 'sortItems')
        _this.setData({
            tabCur: e.currentTarget.dataset.index,
            'goodsOption.queryString': e.detail.value,
            'goodsOption.pageNum': 0,
            'goodsOption.sortItems': sortItems
        });
        _this.getGoods();
    },
    // 改变美颜
    slider1change(e) {
        this.setData({
            'beautyInfo.beauty': e.detail.value
        })
    },
    // 改变美白
    slider2change(e) {
        this.setData({
            'beautyInfo.whiteness': e.detail.value
        })
    },
    // 改变主播描述
    anchorDescChange(e) {
        this.setData({
            'addInfo.anchor_desc': e.detail.value
        });
    },
    // 改变直播间描述
    videoDescChange(e) {
        this.setData({
            'addInfo.video_desc': e.detail.value
        });
    },
    // 开始直播
    async liveStart() {
        let _this = this;
        let addInfo = _this.data.addInfo;
        if(!addInfo.live_image) {
            Wx.showToastError('封面不能为空');
            return false;
        }
        else if(!addInfo.anchor_desc) {
            Wx.showToastError('请添加主播描述');
            return false;
        }
        else if(!addInfo.video_desc) {
            Wx.showToastError('请添加直播间描述');
            return false;
        }
        else if(!addInfo.shop_id) {
            Wx.showToastError('请添加工厂');
            return false;
        }
        else if(addInfo.goods_list.length <= 0) {
            Wx.showToastError('请添加商品');
            return false;
        }
        else if(!addInfo.video_classified) {
            Wx.showToastError('请添加标签');
            return false;
        }
		
		wx.showLoading({
		    title: '加载中'
		});
		
		try{
		
			const checkres1 = await fetch(Api.MsgCheck,{
				  method: 'POST',
				  data:{
						content:addInfo.anchor_desc
					}
			  })
				
			if(checkres1.result.label!==100){
				 try{wx.hideLoading()}catch(err){};
				 Wx.showToastError('主播描述存在敏感内容')
				 return false;
			}
					
			const checkres2 = await fetch(Api.MsgCheck,{
				  method: 'POST',
				  data:{
						content:addInfo.video_desc
					}
			  })
					
			if(checkres2.result.label!==100){
				try{wx.hideLoading()}catch(err){};
				 Wx.showToastError('直播间描述存在敏感内容')
				 return false;
			}
		
		}catch(e){
			Wx.showToastError('msgcheck err: '+e.status+' '+e.error)
			return false
		}
       
        _this.LiveDeleteSell();
        addInfo.goods_list = JSON.stringify(addInfo.goods_list);

        fetch(Api.LiveStart, {
            method: 'POST',
            data: addInfo,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
			try{wx.hideLoading()}catch(err){};
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            _this.setData({
                infoData: res,
                room_id: res.room_id,
                'infoData.video.push_rtmp': res.push_rtmp,
                isAdd: false,
            });
			
			// 推流
			_this.livePush();
			_this.LiveAddSell();
     //        _this.data.livePusher.start({
     //            success: res => {
     //                console.log('推流成功', res)
     //                _this.livePush();
					// _this.LiveAddSell();
     //            },
     //            fail: res => {
     //                console.log('推流失败', res);
     //            }
     //        });
        })
    },
    // 商品提交后台
    LiveAddSell() {
		wx.showLoading({
		    title: '加载中'
		});
        let _this = this;
        let addSellList = _this.data.addSellList;
        for(let i = 0; i < addSellList.length; i++ ) {
            addSellList[i] = Object.assign(addSellList[i], {roomId: _this.data.room_id});
        };
        addSellList = JSON.stringify(addSellList);
        fetch(Api.LiveAddSell, {
            method: 'GET',
            data: {
                'anchorStr': addSellList
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
			wx.hideLoading()
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            _this.setData({
                isAdd: true
            });
            console.log('商品更新成功')
        });
    },
    // 推送到服务器
    livePush() {
        let _this = this;
        fetch(Api.LivePush, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
                room_id: _this.data.room_id,
                status: 1
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            if (res.status == 1) {
                _this.LiveInfo();
            }
            console.log(res, 'livePush')
        });
    },
    // 获取直播信息
    LiveInfo() {
		wx.showLoading({
		    title: '加载中',
			mask:true
		});
        let _this = this;
        fetch(Api.LiveInfo, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
                room_id: _this.data.room_id,
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }, ).then(async (res) => {
			console.log("++++++++++++++直播信息++++",res)
            _this.setData({
                hasRoom: true
            });
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            } else if (res.status == '404') {
                Wx.showToastError(res.error);
                setTimeout(() => {
                    _this.toLiveList();
                }, 1000);
                return false;
            }
            _this.setData({
                'infoData': res,
                'addInfo.live_image': res.video.live_image,
                'addInfo.shop_id': res.video.shop_id,
                'addInfo.shop_name': res.video.shop_name,
                'addInfo.shop_address': res.video.shop_address,
                'addInfo.shop_image': res.video.shop_image,
                group_id: res.video.group_id.toString(),
                account_id: res.tim.account_id+'',
                usersig: res.tim.usersig,
                followCount: res.video.shop_follow_count,
                follow: res.video.is_follow ? true : false,
                shareCount: res.video.share_count,
                greatCount: res.video.like_count,
                anchorid: res.podcast.id,
                next_swiper: 0,
                like_type: res.video.has_like
            });
            // if(!_this.data.isAdd) {
            //     _this.LiveAddSell();
            // }
            if (_this.data.infoData.video.push_rtmp) {
                // 主播端
                if(res.video.live_in == '1') {
                    if(!_this.data.isJoinGroup) {
                       await _this.initTim(res.tim.sdkappid, true);
                    }
                    _this.liveMonitor();
                    _this.setData({
                        liveMonitorTimer: setInterval(() => {
                            _this.liveMonitor()
                        }, 40000)
                    });
                }
                else if(res.video.live_in == '0') {
                    if(_this.data.video_url) {
                        _this.setData({
                            liveHistory: true,
                        });
                    }
                    else {
                        _this.setData({
                            liveStop: true,
                            liveTimes: res.video.starting_time,
                            watchNumber: res.video.watch_number
                        });
                        _this.liveOrderCount();
                        _this.queryAnchororders();
                    }
                }
                else {
                    // 直播结束
                    _this.setData({
                        liveStop: true,
                        liveTimes: res.video.starting_time,
                        watchNumber: res.video.watch_number
                    });
                    _this.liveOrderCount();
                    _this.queryAnchororders();
                }
            }
            else {
                // 用户端
                // _this.getInfoCont();
                if(res.video.live_in == '1') {
                    _this.setData({
                        liveStop: false,
                        liveHistory: false
                    })
                    if(!_this.data.isJoinGroup) {
                        await _this.initTim(res.tim.sdkappid);
                    }
                    _this.LiveUserStatus();
                }
                else if(res.video.live_in == '0') {
                    if(_this.data.video_url) {
                        _this.setData({
                            liveHistory: true,
                        });
                    }
                    else {
                        _this.getNextData();
                        _this.setData({
                            liveStop: true
                        })
                    }
                }
                else {
                    // 回放分开
                    if(_this.data.video_url) {
                        _this.setData({
                            liveHistory: true,
                        });
                    }
                    else {
                        _this.getNextData();
                        _this.setData({
                            liveStop: true
                        })
                    }
                }
            };
			wx.hideLoading()
        });
    },
    // 直播错误
    anchorError(e) {
        console.log('直播错误', e.detail.errMsg);
    },
    // 主播心跳监听
    liveMonitor() {
        let _this = this;
        fetch(Api.LiveMonitor, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
                room_id: _this.data.room_id
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            console.log(res, 'liveMonitor')
        });
    },
    // 停止直播
    liveStop: function () {
        let _this = this;
        wx.showModal({
            title: '您目前正在直播，确认要关闭吗？',
            success(res) {
                console.log(res, 'stop')
                if (res.confirm) {
                    fetch(Api.LiveStop, {
                        method: 'POST',
                        data: {
                            key: _this.data.addInfo.key,
                            room_id: _this.data.room_id
                        },
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                    }).then((res) => {
                        if (res.status == '0') {
                            Wx.showToastError(res.error);
                            return false;
                        }
                        console.log(res, 'liveStop')
                        clearInterval(_this.data.liveMonitorTimer);
                        _this.data.livePusher.stop();
                        _this.setData({
                            liveStop: true,
                            liveTimes: res.time_len,
                            watchNumber:res.watch_number
                        });
                        _this.liveOrderCount();
                        _this.queryAnchororders();
                        if(_this.data.isJoinGroup) {
                            _this.stopTim();
                        }
                    });
                }
            }
        });
    },
    // 去直播列表(改为上一页)
    toLiveList() {
        let _this = this;
        var pages = getCurrentPages();
        if(pages.length == '1') {
            wx.switchTab({
                url: '/pages/live/liveList'
            });
        }
        else {
            wx.navigateBack({
                delta: 1
            });
        }

    },
    // 切换摄像头
    devicePosition() {
        this.data.livePusher.switchCamera()
    },

    // 用户状态
    LiveUserStatus() {
        let _this = this;
        fetch(Api.LiveUserStatus, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            console.log(res, 'LiveUserStatus')
        });
    },
    // 是否显示全部商品(用户端)
    changeUserGoods() {
        this.setData({
            showUserGoods: !this.data.showUserGoods,
            sellGoodsList: []
        });
        if(this.data.showUserGoods) {
            this.getSaleGoods();
        }
    },
    // 是否显示全部商品(主播端)
    changeAnchorGoods() {
        this.setData({
            showAnchorGoods: !this.data.showAnchorGoods
        });
        if(this.data.showAnchorGoods) {
            this.getSaleGoods();
        }
    },
    // 主播端搜索商品
    anchorSearchGoods(e) {
        console.log(e.detail.value, 'e');
        this.getSaleGoods();
    },
    // 主播商品切换
    anchorGoodsTab(e) {
        this.setData({
            anchorGoodsIndex: e.currentTarget.dataset.index,
            sellGoodsList: []
        });
        this.getSaleGoods();
    },
    // 用户端播放状态
    statechange(e) {
        console.log(e.detail.code);
        let _this = this;
        if (e.detail.code == 2006) {
            _this.setData({
                liveStop: true
            });
        };
        if (e.detail.code == '-2301') {
            // _this.LiveInfo();
        }
    },
    // 关注工厂
    follow() {
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        fetch(Api.LiveFollow, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
                shop_id: _this.data.addInfo.shop_id
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            _this.setData({
                isSend: false
            });
            Wx.showToastError(res.error)
            if(res.status == '0') {
                return false;
            }
            _this.setData({
                follow: res.has_focus ? true : false,
                followCount: res.shop_follow_count
            });

        });
    },
    // 点赞
    praise() {
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        clearTimeout(timer1);
        _this.setData({
            isSend: true
        });
        fetch(Api.LivePraise, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
                room_id: _this.data.room_id
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            let arr = _this.data.clickPraise;
            arr.push('1')
            _this.setData({
                isSend: false,
                clickPraise: arr
            });
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            _this.setData({
                greatCount: res.like_count,
                like_type: res.like_type
            });

            timer1 = setTimeout(() => {
                arr = [];
                _this.setData({
                    clickPraise: arr
                });
            }, 2000);
        });
    },
    // 分享
    share() {
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        fetch(Api.LiveShare, {
            method: 'POST',
            data: {
                key: _this.data.addInfo.key,
                room_id: _this.data.room_id
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then((res) => {
            _this.setData({
                isSend: false
            });
            if (res.status == '0') {
                return false;
            }
            _this.setData({
                shareCount: res.share_count
            });
        });
    },
    // IM
    async initTim(SDKAppID, isAnchor) {
        let _this = this;
        let options = {
            SDKAppID: SDKAppID
        }

        tim = TIM.create(options);
        tim.setLogLevel(1);

        // 登录 SDK
		try{
			const timLogin = await tim.login({
				userID: _this.data.account_id,
				userSig: _this.data.usersig
			});
			
			console.log(timLogin.data, '登录成功');
			
			//加入群组
			const imResponse = await tim.joinGroup({
			    groupID: _this.data.group_id,
			    type: TIM.TYPES.GRP_AVCHATROOM
			});
			
			switch (imResponse.data.status) {
			    case TIM.TYPES.JOIN_STATUS_WAIT_APPROVAL: // 等待管理员同意
			        break;
			    case TIM.TYPES.JOIN_STATUS_SUCCESS: // 加群成功
			        console.log('加群成功')
			        _this.setData({
			            isJoinGroup: true,
			            'infoData.viewer.watch_number': +_this.data.infoData.viewer.watch_number + 1
			        });
			        if(!isAnchor) {
						await _this.joinGroups();
					}
			        break;
			    case TIM.TYPES.JOIN_STATUS_ALREADY_IN_GROUP: // 已经在群中
			        _this.setData({
			            isJoinGroup: true
			        });
			        break;
			    default:
			        break;
			}
			
		}catch(imError){
			Wx.showToastError('初始化失败,请重新进入');
			console.warn('TIM初始化失败:', imError);
		}
		
        // 接收消息
        tim.on(TIM.EVENT.MESSAGE_RECEIVED, _this.reciveMsg);

        // 登录被踢
        // let onKickedOut = function (event) {
        //     console.log(event.data.type, '同一设备，同一帐号，多页面登录被踢');
        // };
        // tim.on(TIM.EVENT.KICKED_OUT, onKickedOut);
    },
    async joinGroups(isAnchor) {
        let _this = this;
        var nickName = _this.data.nickName;
        var tips = '欢迎' + nickName + '进入直播间'
        var message = _this.createText(_this.data.group_id, tips, 5);
		
        const imResponse = await tim.sendMessage(message);
		tips = JSON.parse(imResponse.data.message.payload.data);

		var msgList = _this.data.msgList;
		msgList.push(tips);
		if(msgList.length > 1000) {
			msgList = msgList.slice(-1000)
		}
		_this.setData({
			msgList: msgList,
			content: '',
			scrollTo: `item${msgList.length - 1}`,
			showAnchorInput: false
		});
    },
    stopTim() {
        let _this = this;
        if(!_this.data.isJoinGroup) {
            return false;
        }

        //取消监听事件
        tim.off(TIM.EVENT.MESSAGE_RECEIVED, _this.reciveMsg);
        tim.off(TIM.EVENT.SDK_READY, _this.joinGroups);

        if(_this.data.infoData.video.push_rtmp) {
            // 退出Tim
            let quit = tim.logout();
            quit.then(function(imResponse) {
                console.log(imResponse.data, '退出Tim成功');
            }).catch(function(imError) {
                console.warn('退出Tim失败:', imError);
            });
        }
        else {
            //退群
            let quitGroup = tim.quitGroup(_this.data.group_id);
            quitGroup.then(function (imResponse) {
                console.log(imResponse, "退群成功");
                _this.setData({
                    isJoinGroup: false,
                });
                // 退出Tim
                let quit = tim.logout();
                quit.then(function(imResponse) {
                    console.log(imResponse.data, '退出Tim成功');
                }).catch(function(imError) {
                    console.warn('退出Tim失败:', imError);
                });
            }).catch(function (imError) {
                console.warn('quitGroup error:', imError); // 退出群组失败的相关信息
            });
        }
    },
    // 发送消息
    async sendMsg() {
        let _this = this;
        if(!_this.data.content) {
            return
        }
		
		try{
			const checkres = await fetch(Api.MsgCheck,{
					  method: 'POST',
					  data:{
							content:_this.data.content
						}
				  })
					
			if(checkres.result.label!==100){
				 Wx.showToastError('消息中含有敏感词汇')
				 return
			}
		}catch(e){
			Wx.showToastError('msgcheck err: '+e.status+' '+e.error)
			return
		}
				
		
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        // 2. 发送消息
        var message = _this.createText(_this.data.group_id, _this.data.content, 0);
        let promise = tim.sendMessage(message)
        promise.then(function (imResponse) {
            // 发送成功
            console.log(imResponse, '发送成功');
            _this.setData({
                isSend: false
            });
            imResponse.data.message.payload.data = JSON.parse(imResponse.data.message.payload.data);

            var msgList = _this.data.msgList;
            msgList.push(imResponse.data.message.payload.data);
            if(msgList.length > 1000) {
                msgList = msgList.slice(-1000)
            }
            _this.setData({
                msgList: msgList,
                content: '',
                scrollTo: `item${msgList.length - 1}`,
                showAnchorInput: false
            });
        }).catch(function (imError) {
            // 发送失败
            _this.setData({
                isSend: false
            });
            Wx.showToastError('初始化失败,请重新进入');
            console.warn('sendMessage error:', imError)
        })
    },
    // 接收消息
    reciveMsg(event) {
        let _this = this;
        let msg = event.data[0];
        console.log(msg, '接收消息');
        if (msg.payload.data) {
            msg.payload.data = typeof(msg.payload.data) == 'string' ? JSON.parse(msg.payload.data) : msg.payload.data;
            switch (msg.payload.data.type) {
                case 2: //订单消息
                    console.log('接收订单');
                    clearTimeout(timer2);
                    var tips = msg.payload.data.text;
                    var orderList = _this.data.orderList;
                    orderList.push(tips);
                    _this.setData({
                        orderList: orderList
                    });
                    _this.orderAnim();
                    return false;
                    break;
                case 5:
                    var nickName = msg.payload.data.sender.nick_name;
                    var userId = msg.payload.data.sender.user_id;
                    console.log(nickName + '观众进入房间');
                    var tips = '欢迎' + nickName + '进入直播间'

                    if(_this.data.anchorid == userId) {
                        return;
                    }
                    var msgList = _this.data.msgList;
                    msgList.push({
                        type: 5,
                        text: tips
                    });
                    if(msgList.length > 1000) {
                        msgList = msgList.slice(-1000)
                    }
                    _this.setData({
                        msgList: msgList,
                        content: '',
                        scrollTo: `item${msgList.length - 1}`,
                        showAnchorInput: false,
                        'infoData.viewer.watch_number': +_this.data.infoData.viewer.watch_number + 1
                    });

                    return false;
                    break;
                case 6:
                    var nickName = msg.payload.data.sender.nick_name;
                    console.log(nickName, '观众离开房间');
                    _this.setData({
                        'infoData.viewer.watch_number': _this.data.infoData.viewer.watch_number > 0 ?_this.data.infoData.viewer.watch_number - 1 : 0
                    });
                    return false;
                    break;
                case 7:
                    _this.setData({
                        liveStop: true
                    });
                    if(_this.data.isJoinGroup) {
                            _this.stopTim();
                        }
                    _this.getNextData();
                    console.log('主播结束直播消息')
                    break;
                case 10:
                    console.log('主播离开')
                    break;
                case 11:
                    console.log('主播回来')
                    break;
                case 12:
                    console.log('我点亮了主播')
                    break;
                case 17:
                    console.log('主播结束')
                    fetch(Api.LiveStop, {
                        method: 'POST',
                        data: {
                            key: _this.data.addInfo.key,
                            room_id: _this.data.room_id
                        },
                        headers: {
                            'Content-Type': 'application/x-www-form-urlencoded',
                        },
                    }).then((res) => {
                        if (res.status == '0') {
                            Wx.showToastError(res.error);
                            return false;
                        }
                        clearInterval(_this.data.liveMonitorTimer);
                        _this.data.livePusher.stop();
                        _this.setData({
                            liveStop: true,
                            liveTimes: res.time_len,
                            watchNumber:res.watch_number
                        });

                        if(_this.data.isJoinGroup) {
                            _this.stopTim();
                        }
                    });
                    break;

                case 18:
                    console.log('用户端主播结束');
                    _this.setData({
                        liveStop: true
                    });
                    if(_this.data.isJoinGroup) {
                            _this.stopTim();
                        }
                    _this.getNextData();
                    return false;
                    break;
                case 41:
                    console.log('警告消息')
                    clearTimeout(timer2);
                    var tips = msg.payload.data.desc;
                    var orderList = _this.data.orderList;
                    orderList.push(tips);
                    _this.setData({
                        orderList: orderList
                    });
                    _this.orderAnim();
                    return false;
                    break;
                default:
                    break;
            }
            var msgList = _this.data.msgList;
            msgList.push(msg.payload.data);
            if(msgList.length > 1000) {
                msgList = msgList.slice(-1000)
            }
            _this.setData({
                msgList: msgList,
                scrollTo: `item${msgList.length - 1}`
            });
        }
    },
    // 文本框内容
    msgContent(e) {
        this.setData({
            content: e.detail.value
        });
    },
    //创建消息
    createText(toID, text, type, icon){
        var icon = icon || '';
        var payload = {
            data: JSON.stringify({
                "type": type,
                "text": text,
                "sender": {
                    "user_id": this.data.account_id,
                    "nick_name": this.data.nickName,
                },
                "icon":icon
            })
        }
        let message = tim.createCustomMessage({
            to: toID,
            conversationType: TIM.TYPES.CONV_GROUP,
            payload: payload
        });
        return message;
    },
    // 主播评论
    showAInput() {
        this.setData({
            showAnchorInput: true
        });
    },
    // 进入动画
    joinAnim:function(){
        let _this = this;

        _this.setData({
            joinAnim: true,
        });
        let joinList = _this.data.joinList;
        timer1 = setTimeout(() => {
            joinList.splice(0, 1);
            if(joinList.length > 0) {
                _this.setData({
                    joinList: joinList,
                    joinAnim: false,
                });
                _this.joinAnim();
            }
            else {
                _this.setData({
                    joinList: joinList,
                    joinAnim: false,
                });
            }
        }, 2000)
    },
    // 订单动画
    orderAnim:function(){
        let _this = this;

        _this.setData({
            orderAnim: true,
        });
        let orderList = _this.data.orderList;
        timer2 = setTimeout(() => {
            orderList.splice(0, 1);
            if(orderList.length > 0) {
                _this.setData({
                    orderList: orderList,
                    orderAnim: false,
                });
                _this.orderAnim();
            }
            else {
                _this.setData({
                    orderList: orderList,
                    orderAnim: false,
                });
            }
        }, 4000)
    },
    // 跳转工厂基地
    goFactory(e) {
        Router.navTo('LiveFactory', '?shop_id=' + e.currentTarget.dataset.shopid);
    },
    // 获取在售商品列表
    getSaleGoods() {
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        wx.showLoading({
            title: '加载中'
        });
        fetch(Api.LiveSellList, {
            method: 'POST',
            data: {
                customerId: _this.data.anchorid,
                storeId: _this.data.addInfo.shop_id,
                sellType: _this.data.anchorGoodsIndex,
                spuName: _this.data.soInputVal,
                roomId: _this.data.room_id
            },
        }).then((res) => {
            try{wx.hideLoading()}catch(err){};
            _this.setData({
                isSend: false
            });
            if (res.flag == '0') {
                return false;
            }
            _this.setData({
                sellGoodsList: res.data,
                sellPage: +_this.data.sellPage+ 1
            });
        });
    },
    // 开播清除未开售商品
    LiveDeleteSell() {
        let _this = this;
        fetch(Api.LiveDeleteSell, {
            method: 'POST',
            data: {
                customerId: _this.data.anchorid,
                spuId: _this.data.addInfo.shop_id,
                sellType: 0
            },
        }).then((res) => {
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }

            console.log('商品清除成功')
        });
    },
    // 未开售到已开售商品
    LiveupdateSell(e) {
        let _this = this;
        let id = e.currentTarget.dataset.id;
        fetch(Api.LiveupdateSell, {
            method: 'POST',
            data: {
                id: id,
                sellType: 1
            },
        }).then((res) => {
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            _this.getSaleGoods();
        });
    },
    // 获取工厂信息
    getInfoCont() {
        let _this = this;
        fetch(Api.StoreInfo, {
            method: 'GET',
            data: {
                storeId: _this.data.addInfo.shop_id
            },
        }).then(res => {
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            _this.setData({
                infoCont: res.data
            });
        })
    },
    // 改变主播描述
    soInputVal(e) {
        this.setData({
            soInputVal: e.detail.value
        });
    },
    // 直播结束订单量查询
    liveOrderCount() {
        console.log('结束订单查询')
        let _this = this;
        fetch(Api.LiveOrderCount, {
            method: 'POST',
            data: {
                storeId: _this.data.addInfo.shop_id,
                roomId: _this.data.room_id,
                anchorId: _this.data.anchorid
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then(res => {
            if (res.status == '0') {
                Wx.showToastError(res.error);
                return false;
            }
            _this.setData({
                orderCount: res.data.orderCount,
                orderAmount: res.data.orderAmount
            });
        })
    },
    // 直播结束成交订单
    queryAnchororders() {
        console.log('直播结束成交订单')
        let _this = this;
        if(_this.data.isSend) {
            return false;
        }
        _this.setData({
            isSend: true
        });
        wx.showLoading({
            title: '加载中'
        });
        fetch(Api.QueryAnchororders, {
            data: {
                roomId: _this.data.room_id,
                anchorId: _this.data.anchorid,
                pageNum: _this.data.dealOrderPage,
                storeId: _this.data.addInfo.shop_id
            },
        }).then(res => {
            try{wx.hideLoading()}catch(err){};
            _this.setData({
                isSend: false
            });
            if (res.status == '0' || res.code) {
                Wx.showToastError(res.error);
                return false;
            }
            if(res.data.length <= 0) {
                _this.setData({
                    noData: true
                });
                return false;
            }
            let arr = _this.data.dealOrderList;
            if(_this.data.dealOrderList == '0') {
                arr = [];
            };
            arr = arr.concat(res.data);
            _this.setData({
                dealOrderList: arr,
                dealOrderPage: +_this.data.dealOrderPage+ 1
            });
        });
    },
    // 去订单详情
    toOrderDetail: function (e) {
        Router.navTo('OrderDetail', "?id=" + e.currentTarget.dataset.id)
    },
    // 成交订单加载更多
    scrollDealOrder() {
        if(this.data.noData) {
            return false;
        }
        this.queryAnchororders();
    },
    // 输入框失焦
    blur() {
        this.setData({
            showAnchorInput: false,
        })
    },
    // 用户直播结束跳转
    swiperTo(e) {
        this.setData({
            moveTop: 0
        });
        this.setData({
            room_id: this.data.next_room_id,
            isSend: false
        });
        this.LiveInfo();
    },
    // 获取数据
    getNextData() {
        let _this = this;
        _this.setData({
            no_next: true
        });
        fetch(Api.LiveList, {
            method: 'POST',
            data: {
                page: _this.data.page
            },
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then(res => {
            if (res.status == '0') {
                return false;
            }
            if(res.list.length > 1) {
                let i = 0;
                if(res.list[0].room_id != _this.data.room_id) {
                    i = 0;
                }
                else {
                    i = 1;
                }
                _this.setData({
                    no_next: false,
                    next_room_id: res.list[i].room_id,
                    next_live_image: res.list[i].live_image ? res.list[i].live_image : _this.data.live_image
                });
            }
            else if(res.list.length == 1) {
                if(res.list[0].room_id == _this.data.room_id) {
                    _this.setData({
                        no_next: true
                    });
                    return false;
                }
                _this.setData({
                    no_next: false,
                    next_room_id: res.list[0].room_id,
                    next_live_image: res.list[0].live_image ? res.list[0].live_image : _this.data.live_image
                });
            }
            else {
                _this.setData({
                    no_next: true
                });
            }
        });
    },
    // 获取分类
    getTags () {
        let _this = this;
        wx.showLoading({
          title: '加载中',
        });
        fetch(Api.LiveClassify, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        }).then(res => {
            try{wx.hideLoading()}catch(err){};
            if(res.status == '0') {
                Wx.showToastError(res.error)
                return false;
            }
            _this.setData({
                tagsList: res.list
            });
        })
    },
    // 是否显示分类列表
    changeTags() {
        let _this = this;
        _this.setData({
            showTags: !_this.data.showTags
        });
        if(!_this.data.tagsList.length) {
            _this.getTags();
        }
    },

    // 分类标签修改
    tagsChange(e) {
        let tagsList = this.data.tagsList;
        let val = e.detail.value;
        let arr = [];
        tagsList.forEach((item, index) => {
            tagsList[index].checked = false;
        });
        val.forEach((item, index) => {
            this.data.tagsList.forEach((item2, index2) => {
                if(item == item2.classified_id) {
                    tagsList[index2].checked = true;
                    arr.push(this.data.tagsList[index2].title)
                }
            });
        });
        this.setData({
            tagsList: tagsList,
            'addInfo.video_classified': val.join(','),
            tagsName: arr.join(',')
        })
    },
})
